<?php

namespace App\Services\Admin;

use App\Models\ClassBaseInfo;
use App\Models\ClassBaseInfo as ClassBaseInfoModel;
use App\Models\ClassBaseInfoSuspension;
use App\Models\ClassBaseInfoTeacher;
use App\Models\UserSubscribe;
use App\Services\Admin\ClassBaseTime;
use App\Models\ClassBaseTime as ClassBaseTimeModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Reservation extends Base
{
    /**
     * 查看该预约的客户的列表
     * @param $class_base_info_id
     * @param $time
     */
    public static function user_subscribe($class_base_info_id, $time)
    {
        $start_time = "{$time} 00:00:00";
        $end_time = "{$time} 23:59:59";

        $where[] = ['class_base_info_id', $class_base_info_id];
        $where[] = ['class_time', ">=", $start_time];
        $where[] = ['class_time', "<=", $end_time];

        //查询已预约
        return (new UserSubscribe())->where($where);
    }

    /**
     * 组装上课时间
     */
    public static function check_class_time($reservation_lists = [])
    {
        $class_time_info = [];

        foreach ($reservation_lists as $v) {

            $input['class_weeks'] = $v['class_week'];
            $input['class_time'] = $v['class_time']['time_start'] . "~" . $v['class_time']['time_end'];

            $class_time_info[] = $input;
        }

        return json_encode($class_time_info);
    }

    public static function lists()
    {

        $input = request()->all();

        $where = [];

        if (!empty($input['store_id'])) $where[] = ['store_id', $input['store_id']];
        //if (!empty($input['sear_value'])) $where[] = ['class_name', 'like', '%' . $input['sear_value'] . '%'];
        if (!empty($input['classroom'])) $where[] = ['class_classroom_id', $input['classroom']];
        if (!empty($input['class_base'])) $where[] = ['class_base_id', $input['class_base']];

        if (!empty($input['week'])) {
            $where[] = ['class_week', $input['week']];
        }

        if (!empty($input['day'])) {
            $week_day = date("N", strtotime("{$input['day']}"));

            $where[] = ['class_week', $week_day];
        }

        $result = (new ClassBaseInfoModel)->with(['store', 'class_base' => function ($class_base) {
            $class_base->with(['numbering'])->select('id', 'class_name', 'class_base_numbering_id', 'class_price');
        }, 'class_base_info_teacher' => function ($teacher) use ($input) {

            $where = [];

            if (!empty($input['day'])) {
                $where[] = ['designated_date', 'like', '%' . $input['day'] . '%'];
                $where[] = ['is_common', '=', 1, 'OR'];
            } else {
                $where[] = ['is_common', 1];
            }

            $teacher->with(['teacher' => function ($query) {
                $query->select('id', 'teacher_name');
            }])->where($where);

        }, 'classsroom' => function ($classroom) {
            $classroom->select('id', 'numbering');
        }, 'class_time' => function ($class_time) {
            $class_time->select('id', 'time_start', 'time_end', 'duration')->orderBy('time_start', 'asc')->orderBy('time_end', 'asc');
        }, 'quarterly', 'class_base_info_suspension' => function () {

        }])->whereHas('quarterly', function ($quarterly) use ($input) {
            if (!empty($input['day'])) {
                $where = [];
                $where[] = ['start_time', '<=', $input['day']];
                $where[] = ['end_time', '>=', $input['day']];
                $where[] = ['is_display', 1];
                $quarterly->where($where);
            }
        })->where($where);

        if(!empty($input['day'])) {
            $result = $result->whereRaw("IF(designated_date != '',designated_date like '%" . $input['day'] . "%',1=1)");
        }

        if (!empty($input['user_rank_id'])) {
            $result = $result->where('user_rank_id', 'like', '%' . $input['user_rank_id'] . '%');
        }

        if (!empty($input['teacher'])) {
            $class_base_info_id = (new ClassBaseInfoTeacher())->where('teacher_id', $input['teacher'])->pluck('class_base_info_id')->toArray();
            $result = $result->whereIn('id', $class_base_info_id);
        }

        $result = $result->orderBy('class_week', 'asc');

        return $result;
    }

    /**
     * 用于添加工作计划任务时
     * @param int $classroom_id
     * @param string $time
     * @return \Illuminate\Database\Eloquent\Builder
     *
     */
    public static function lists_add($classroom_id = 0, $time = '')
    {
        $home = self::home($classroom_id, $time);

        $where[] = ['class_classroom_id', $classroom_id];
        $where[] = ['class_week', $home['base_time']['week']];

        $input['day'] = $time;

        return (new ClassBaseInfoModel)->with(['store', 'class_base' => function ($class_base) {
            $class_base->with(['numbering'])->select('id', 'class_name', 'class_base_numbering_id');
        }, 'teacher' => function ($teacher) {
            $teacher->select('id', 'teacher_name');
        }, 'classsroom' => function ($classroom) {
            $classroom->select('id', 'numbering');
        }, 'class_time' => function ($class_time) {
            $class_time->select('id', 'time_start', 'time_end')->orderBy('time_start', 'asc')->orderBy('time_end', 'asc');
        }, 'quarterly', 'class_base_info_teacher' => function ($teacher) use ($input) {

            $where = [];

            if (!empty($input['day'])) {
                $where[] = ['designated_date', 'like', '%' . $input['day'] . '%'];
                $where[] = ['is_common', '=', 1, 'OR'];
            } else {
                $where[] = ['is_common', 1];
            }

            $teacher->with(['teacher' => function ($query) {
                $query->select('id', 'teacher_name');
            }])->where($where);

        }])->whereHas('quarterly', function ($quarterly) use ($input) {
            if (!empty($input['day'])) {
                $where[] = ['start_time', '<=', $input['day']];
                $where[] = ['end_time', '>=', $input['day']];
                $where[] = ['is_display', 1];
                $quarterly->where($where);
            }
        })->where($where)->orderBy('class_week', 'asc');
    }

    public static function info($id)
    {
        return (new ClassBaseInfoModel)->where('id', $id)->first();
    }

    //查询已预约该时间端跟课室是否有预约
    public static function is_appointment_number()
    {

        $time = request()->time ?? 0;
        $class_classroom_id = request()->class_classroom_id ?? 0;
        $designated_date = request()->designated_date ?? 0;

        //查询是否重复设置
        $result = Reservation::lists_add($class_classroom_id, $time)->orderBy('class_time', 'asc')->get();

        if(!empty($designated_date)) {

            $designated_date_array = explode(',',$designated_date);

            //当指定日期时则判断当前的时间范围是否有上课时间冲突，否则为空时则判断全局周期的时间范围
            foreach ($result as $k => $v) {
                if (!empty($v->designated_date)) {
                    $designated_date_result = explode(',',$v->designated_date);

                    //判断是否在时间范围内
                    if (empty(array_intersect($designated_date_array, $designated_date_result))) {
                        unset($result[$k]);
                    }
                }
            }

        }

        $bool = 0;

        foreach ($result as $k => $v) {
            if (self::checkIsBetweenTime($v)) {
                $bool = 1;
                break;
            }
        }

        return $bool;

    }


    /**
     * 判断是否已经添加过了
     * @param $start 开始时分  eg:10:30
     * @param $end  结束时分   eg:15:30
     * @param $select_start  数据库的时分秒   eg:15:30
     * @param $select_end  数据库的时分秒   eg:15:30
     * @return: bool  1：在范围内，0:没在范围内
     * @author:mzc
     * @date:2018/8/9 10:46
     */
    public static function checkIsBetweenTime($get)
    {
        $start = request()->start_string ?? 0;
        $end = request()->end_string ?? 0;

        $class_time_string = explode("~", $get->class_time);

        $select_start = $class_time_string[0];
        $select_end = $class_time_string[1];

        $select_start = strtotime("{$select_start}");//获得指定分钟时间戳，00:00
        $start = strtotime("{$start}");//获得指定分钟时间戳，00:00

        $select_end = strtotime("{$select_end}");//获得指定分钟时间戳，01:00
        $end = strtotime("{$end}");//获得指定分钟时间戳，01:00

        $result = 0;

        if (($select_start < $start && $select_end > $end || $select_start >= $start && $select_start <= $end || $select_end >= $start && $select_end <= $end)) {
            $result = 1;
        }

        return $result;
    }


    public static function add($param = [])
    {
        $param['class_time_id'] = self::class_bass_insert();

        $add['time_start'] = $param['start_hour'] . ':' . $param['start_minute'];
        $add['time_end'] = $param['end_hour'] . ':' . $param['end_minute'];
        $param['class_duration'] = ClassBaseTime::duration($add['time_start'], $add['time_end']);
        $time = $param['time'];

        unset($param['start_hour']);
        unset($param['start_minute']);
        unset($param['end_hour']);
        unset($param['end_minute']);
        unset($param['start_string']);
        unset($param['end_string']);
        unset($param['time']);

        $open_an_appointment = $param['open_an_appointment'];

        unset($param['open_an_appointment']);

        $class_base_info_id = (new ClassBaseInfoModel)->insertGetId($param);

        $insert = (new ClassBaseInfoTeacher());

        $insert->class_base_info_id = $class_base_info_id;
        $insert->teacher_id = $param['teacher_id'];
        $insert->is_common = 1;

        $insert->save();

        self::class_base_info_suspension_common($open_an_appointment, $class_base_info_id, $time);
    }

    public static function edit($id, $param = [])
    {
        $param['class_time_id'] = self::class_bass_insert();

        $add['time_start'] = $param['start_hour'] . ':' . $param['start_minute'];
        $add['time_end'] = $param['end_hour'] . ':' . $param['end_minute'];
        $param['class_duration'] = ClassBaseTime::duration($add['time_start'], $add['time_end']);
        $time = $param['time'];
        $open_an_appointment = $param['open_an_appointment'];

        unset($param['open_an_appointment']);
        unset($param['start_hour']);
        unset($param['start_minute']);
        unset($param['end_hour']);
        unset($param['end_minute']);
        unset($param['start_string']);
        unset($param['end_string']);
        unset($param['time']);

        self::class_base_info_suspension_common($open_an_appointment, $id, $time);

        return (new ClassBaseInfoModel)->where('id', $id)->update($param);
    }

    /**
     * 当前时间公共录入
     * @param $open_an_appointment
     * @param $class_base_id
     * @param $time
     */
    public static function class_base_info_suspension_common($open_an_appointment, $class_base_info_id, $time)
    {
        if (in_array($open_an_appointment, ['1', '-1'])) {

            $supspension_where[] = ['class_base_info_id', $class_base_info_id];
            $supspension_where[] = ['suspension_time', "{$time} 00:00:00"];
            (new ClassBaseInfoSuspension())->where($supspension_where)->delete();

            $class_base_appointment['class_base_info_id'] = $class_base_info_id;
            $class_base_appointment['suspension_time'] = "{$time} 00:00:00";

            if ($open_an_appointment == -1) {
                $class_base_appointment['is_open'] = "-1";
            } else {
                $class_base_appointment['is_open'] = "1";
            }

            (new ClassBaseInfoSuspension())->insert($class_base_appointment);

        }
    }

    public static function del($id)
    {
        return (new ClassBaseInfoModel)->where('id', $id)->delete();
    }

    public static function home($class_classroom_id, $time)
    {
        $w = date('N', strtotime("{$time}"));

        $base_time['week'] = $w;
        $base_time['week_name'] = ClassBaseTime::week_result()[$w];

        $result = [
            'classroom_nubering' => Classroom::info($class_classroom_id)->numbering,
            'base_time' => $base_time
        ];

        return $result;
    }

    //查询预约人数
    public static function class_subscribe_number($class_base_info_id, $status = [])
    {
        $input = request()->all();

        $start_time = "{$input['day']} 00:00:00";
        $end_time = "{$input['day']} 23:59:59";

        $class_status = [1,2,5,7];

        if(!empty($status)){
            $class_status = $status;
        }

        $class_subscribe_number = (new UserSubscribe)->ClassSubscribeNumber($class_base_info_id, $start_time, $end_time, $class_status);

        return $class_subscribe_number;
    }

    //查询该时间点是否已被预约
    public static function class_teacher_id()
    {
        $base_time_id = request()->base_time_id ?? 0;
        $week_id = request()->week_id ?? 0;
        return (new ClassBaseInfo())->where('class_time_id', $base_time_id)->where('class_week', $week_id)->pluck('teacher_id')->toArray();
    }

    //添加時間
    public static function class_bass_insert()
    {
        $start_hour = request()->start_hour ?? 0;
        $start_minute = request()->start_minute ?? 0;
        $end_hour = request()->end_hour ?? 0;
        $end_minute = request()->end_minute ?? 0;
        $class_week = request()->class_week ?? 0;

        $add['time_start'] = $start_hour . ':' . $start_minute;
        $add['time_end'] = $end_hour . ':' . $end_minute;
        $add['duration'] = ClassBaseTime::duration($add['time_start'], $add['time_end']);
        $add['week'] = $class_week;

        $where[] = ['time_start', $add['time_start']];
        $where[] = ['time_end', $add['time_end']];
        $where[] = ['week', $class_week];
        $class_base_time = ClassBaseTimeModel::where($where)->first();
        if (!empty($class_base_time->id)) return $class_base_time->id;

        return ClassBaseTime::add($add);
    }

    //时间周期逆转
    public static function class_bass_week($value = '')
    {
        switch ($value) {
            case '星期一':
                $value = 1;
                break;
            case '星期二':
                $value = 2;
                break;
            case '星期三':
                $value = 3;
                break;
            case '星期四':
                $value = 4;
                break;
            case '星期五':
                $value = 5;
                break;
            case '星期六':
                $value = 6;
                break;
            case '星期日':
                $value = 7;
                break;
        }

        return $value;
    }

    /**
     * 当前时间控制
     * @param array $class_bass_info 当前数据
     * @param  $time                    当前时间
     * return $open_an_appointment      0：没有打开预约  1：当前时间开放预约  -1：当前时间关闭预约
     */
    public static function current_control_time($class_bass_info = [], $time = '')
    {
        $open = [];
        $shut = [];

        array_walk($class_bass_info, function ($value) use (&$open, &$shut) {
            if ($value['is_open'] == 1) {
                $open[] = $value['suspension_time'];
            } else if ($value['is_open'] == -1) {
                $shut[] = $value['suspension_time'];
            }
        });

        $suspension_time = array_column($class_bass_info, 'suspension_time');

        $open_an_appointment = 0;

        //判断是否已开启预约
        if (in_array("{$time} 00:00:00", $shut)) {
            $open_an_appointment = -1;
        } else if (in_array("{$time} 00:00:00", $open)) {
            $open_an_appointment = 1;
        }

        return $open_an_appointment;
    }

    /**
     * 查询老师列表
     * @param int $class_base_info_id 课程安排
     */
    public static function class_bass_info_teacher($class_base_info_id = 0)
    {
        $all_input = request()->all();

        $where = [];

        $where[] = ['class_base_info_id', $class_base_info_id];

        if (!empty($all_input['class_time'])) {
            $where[] = ['designated_date', 'like', '%' . $all_input['class_time'] . '%'];
        }

        return (new ClassBaseInfoTeacher())->whereHas('teacher', function ($query) use ($all_input) {

            $where = [];

            if (!empty($all_input['teacher_name'])) {
                $where[] = ['teacher_name', 'like', '%' . $all_input['teacher_name'] . '%'];
            }

            $query->where($where);

        })->where($where);
    }

    /**
     * 老師安排刪除
     * @param int $class_base_info_id
     * @param int $teacher_id
     */
    public static function class_bass_info_teacher_del($class_base_info_id = 0, $teacher_id = 0)
    {
        return (new ClassBaseInfoTeacher())->where('class_base_info_id', $class_base_info_id)->where('teacher_id', $teacher_id)->delete();
    }

    public static function class_bass_info_teacher_do()
    {
        $all = request()->all();

        DB::beginTransaction();
        try {

            $insert = (new ClassBaseInfoTeacher());

            $select = $insert->where('class_base_info_id', $all['class_base_info_id']);

            $designated_date = $select->pluck('designated_date')->toArray();

            if ($all['designated_date'] && $all['is_common'] == -1) {
                $bool = 1;

                $input_designated_date = explode(",", $all['designated_date']);

                foreach ($designated_date as $v) {

                    //合并数组，用于判断是否有上课时间相冲
                    $designated_date_merge = array_merge($v, $input_designated_date);

                    if (count($designated_date_merge) != count(array_unique($designated_date_merge))) {
                        $bool = 0;
                        break;
                    }

                }

                if (!$bool) throw new \Exception('上課時間跟其他老師衝突!');
            }

            if ($all['is_common'] == 1) {
                $select->update(['is_common' => '-1']);
            }

            $insert->class_base_info_id = $all['class_base_info_id'];
            $insert->designated_date = $all['designated_date'];
            $insert->teacher_id = $all['teacher_id'];
            $insert->is_common = $all['is_common'];
            $insert->save();


            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();
            return ['bool' => false, 'message' => $e->getMessage()];
        }

        return ['bool' => true, 'message' => ''];
    }

    /**
     * 提取老师数据  根据时间安排老师上课
     * @param array $class_base_info_teacher
     */
    public static function class_bass_info_teacher_arr($class_base_info_teacher = [], $time = '')
    {
        $teacher = [
            'id' => 0,
            'teacher_name' => '',
        ];

        if (empty($class_base_info_teacher)) return $teacher;

        $is_common = array_column($class_base_info_teacher, 'is_common');

        $common_key = '';

        //有当前时间
        array_walk($class_base_info_teacher, function ($value, $key) use (&$teacher, $is_common, $time, &$common_key) {

            if (in_array('-1', $is_common)) {

                if ($time == '') {
                    if ($value['is_common'] == '-1') $teacher = $value['teacher'];
                } else {
                    if (!empty($value['designated_date'])) {
                        if ($value['is_common'] == '-1' && in_array($time, $value['designated_date'])) $teacher = $value['teacher'];
                    }
                }

                if ($value['is_common'] == '1') $common_key = $key;

            } else {

                if ($value['is_common'] == '1') $teacher = $value['teacher'];

            }

            if ($teacher['id'] != '0') return;

        });

        //当指定时间也没有上课老师时查看是否有公共老师上课
        if (empty($teacher['id'])) {
            if ($common_key !== '') {
                $teacher = $class_base_info_teacher[$common_key]['teacher'];
            }
        }

        return $teacher;
    }

    /**
     * 单个老师与企业
     */
    public static function class_bass_info_teacher_result($class_base_info_id = 0)
    {
        return (new ClassBaseInfoTeacher())->with(['teacher'])->where('class_base_info_id', $class_base_info_id);
    }

    /**
     * 修改等级
     * @param array $class_base_info_id
     * @param int $user_rank_id
     */
    public static function class_base_info_edit_level($class_base_info_id = [], $user_rank_id = 0)
    {
        return (new ClassBaseInfo())->whereIn('id', $class_base_info_id)->update(['user_rank_id' => $user_rank_id]);
    }
}
